import db from "../models/index.js";
import {Op} from "sequelize";

let depot = db.depot;
let depotDao = {};

// 创建仓库物品
depotDao.add = async (name, unit, amount, cost, raw_meterial, company_id, t) => {
  let is_delete = 0;
  return depot.create({
    name, unit, amount, cost, raw_meterial, company_id, is_delete
  }, {transaction: t});
};

// 逻辑删除仓库物品
depotDao.delete = async (id, t) => {
  if(!t) {
    return depot.update({is_delete: 1}, {where: {id}});
  }
  return depot.update({is_delete: 1}, {where: {id}, transaction: t});
};

// 获取公司仓库列表 逻辑删除的不显示
depotDao.getCompanyDepotList = async (company_id) => {
  return depot.findAll({
    where: {
      company_id,
      is_delete: 0
    },
    raw: true
  });
};

// 获取仓库物品详情
depotDao.getDepotDetail = async (id, t) => {
  if(!t) {
    return depot.findOne({
      where: {
        id
      },
      raw: true
    });
  }
  return depot.findOne({
    where: {
      id
    },
    raw: true,
    transaction: t,
    lock: true
  });
};

// 获取仓库删除的物品列表
depotDao.getDepotDeleteList = async (company_id) => {
  return depot.findAll({
    where: {
      company_id,
      is_delete: 1
    },
    raw: true
  });
};

// 更新仓库物品
depotDao.updateDepot = async (id, name, unit, amount, cost, raw_meterial, t) => {
  return depot.update({name, unit, amount, cost, raw_meterial}, {where: {id}, transaction: t});
};

// 更新仓库物品数量
depotDao.updateDepotAmount = async (id, amount, t) => {
  return depot.update({amount}, {where: {id}, transaction: t});
};

// 根据名称判断是否存在
depotDao.isExistByName = async (name, company_id) => {
  let res = await depot.findOne({
    where: {
      name,
      company_id
    },
    raw: true
  });
  return !!res;
};

// 查询仓库物品是否属于该公司
depotDao.isBelongToCompany = async (id, company_id) => {
  let res = await depot.findOne({
    where: {
      id,
      company_id
    },
    raw: true
  });
  return !!res;
};


export default depotDao;
